﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using RSSReader.MobileClient.Model;
using System.IO.IsolatedStorage;


namespace RSSReader.MobileClient.ViewModel
{
    class UserViewModel
    {
        public LUser Usr { get; set; }
        public WCFWebRoleService.DataDistributorClient UserInfo = new WCFWebRoleService.DataDistributorClient();
        public AsyncDataManager AsyncDM { get; set; }

        public UserViewModel()
        {
            Usr = new LUser("","");

            if (IsolatedStorageSettings.ApplicationSettings.Count > 0)
                GetSavedUserId();
            else 
                Usr.UserId = null;
        }

        public void GetUserId(AsyncDataManager a, string Username, string password)
        {
            if (IsolatedStorageSettings.ApplicationSettings.Count > 0)
            {
                GetSavedUserId();
            }
            else
            {
                Usr = new LUser(Username, password);
                AsyncDM = a;
                try
                {
                    UserInfo.GetUserCompleted += new EventHandler<WCFWebRoleService.GetUserCompletedEventArgs>(CallBackUserId);
                    UserInfo.GetUserAsync(Usr.UserName, Usr.Password);
                }
                catch
                {

                }
            }
        }

        private void CallBackUserId(object sender, WCFWebRoleService.GetUserCompletedEventArgs e)
        {
            try
            {
                Usr.UserId = e.Result.Id;
                Usr.Email = e.Result.Email;
                AsyncDM.ManageCallbacks("GotUserId");
            }
            catch
            {

            }
        }

        public void SaveUserId()
        {
            IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings;

            if (settings.Contains(Usr.UserId))
            {
                settings[Usr.UserId] = Usr;
            }
            else
            {
                settings.Add(Usr.UserId, Usr.GetCopy());
            }
        }

        public void GetSavedUserId()
        {
            foreach (Object o in IsolatedStorageSettings.ApplicationSettings.Values)
            {
                Usr = (LUser)o;
            }
        }
    }
}
